package com.czt.mail.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * @author czt
 * @version 1.0
 * {@desc}
 * @date 2024/8/2 14:49
 */
@Configuration
public class SubscriberCfg {

    public static final String CHANNEL_NAME = "websocketMsg";
    public static final String PATTERN_CHANNEL = "websocket*";

    @Autowired
    private Sub1 sub1;

    @Autowired
    private Sub2 sub2;

    //声明消费者
    @Bean
    public MessageListenerAdapter sub1Adapter() {
        return new MessageListenerAdapter(sub1);
    }

    @Bean
    public MessageListenerAdapter sub2Adapter() {
        return new MessageListenerAdapter(sub2,"receiveMessage");
    }

    //绑定消费者和管道
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        container.addMessageListener(sub1Adapter(), new ChannelTopic(CHANNEL_NAME));
        container.addMessageListener(sub2Adapter(), new PatternTopic(PATTERN_CHANNEL));
        return container;
    }
}
